@ts-nocheck
<template>
  <el-tooltip content="扇区预设" placement="top-end">
    <el-button link icon="EditPen" @click="open"></el-button>
  </el-tooltip>
  <el-dialog
    v-model="showConfigPlanning"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    width="960px"
    top="48px"
    append-to-body
    title="预设扇区布局"
    draggable
    center
  >
    <div class="planner-wrapper-outer">
      <div
        class="planner-wrapper-seat"
        style="
          margin-bottom: 16px;
          font-size: 12px;
          padding: 12px 24px;
          display: flex;
          align-items: center;
          color: rgba(128, 128, 128, 1);
        "
        :closable="false"
        show-icon
      >
        <el-icon :size="48">
          <InfoFilled />
        </el-icon>
        <ul style="margin-left: 36px">
          <li>保存席位预设不会覆盖实际扇区布局；</li>
          <li>预设扇区布局用于帮助管制员提前了解即将生效的扇区布局；</li>
          <li>
            预设扇区布局保存后会在界面右上方显示即将生效提示，点击可查看；
          </li>
          <li>实际扇区布局与预设扇区布局相同时，将清空预设扇区布局；</li>
          <li v-if="isStoped" style="color: var(--el-color-warning)">
            在数据更新被禁用时，单击覆盖当前状态，可将该页面的设置覆盖至实际扇区状态。
          </li>
        </ul>
      </div>
      <div class="planner-wrapper-inner">
        <div class="planner-wrapper-seat" v-for="seat in planningArray">
          <div class="planner-wrapper-seat-title">
            <span style="display: flex; align-items: center">
              <span>{{ seat.seatName }}</span>
              <!-- <el-divider direction="vertical"></el-divider> -->
            </span>
            <!-- <span>{{ seat.seatName }}</span> -->
            <span style="display: flex; align-items: center">
              <span
                style="
                  font-size: 12px;
                  padding-right: 8px;
                  text-decoration: line-through;
                  color: rgba(128, 128, 128, 0.5);
                "
                v-if="seat.frequency != seat.planningFrequency"
              >
                &nbsp;{{
                  seat.frequency == null ? "未设置" : seat.frequency
                }}&nbsp;
              </span>
              <el-icon v-if="seat.frequency != seat.planningFrequency">
                <DArrowRight />
              </el-icon>
              <!-- <el-tag type="warning" size="small">
                  {{ seat.planningFrequency }}
                </el-tag> -->
              <el-select
                v-model="seat.planningFrequency"
                size="small"
                placeholder="未设置"
                :disabled="seat.sectorCodes.length != 0"
                style="width: 80px; margin-left: 12px"
              >
                <el-option
                  v-for="frequency in frequencies"
                  :label="frequency.value"
                  :value="frequency.value"
                >
                </el-option>
              </el-select>
            </span>
          </div>
          <draggable
            class="planner-wrapper-seat-content"
            v-model="seat.planningSectorCodes"
            group="sector"
            :sort="true"
            :animation="500"
            @start="drag = true"
            @end="drag = false"
            item-key="id"
          >
            <template #item="{ element }">
              <el-tag
                class="planner-sector-code"
                :type="seat.sectorCodes.indexOf(element) > -1 ? '' : 'warning'"
                >{{ element }}</el-tag
              >
            </template>
          </draggable>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="planner-wrapper-command">
        <el-button type="primary" link @click="close">取消</el-button>
        <el-button type="primary" link @click="clear">清除</el-button>
        <el-button type="primary" @click="save">保存席位预设</el-button>
        <el-button type="warning" @click="cover" v-if="isStoped">
          <span>覆盖当前状态</span>
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import useSeatStore from "@/store/seat.js";
import draggable from "vuedraggable";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

const seatStore = useSeatStore();
const planningArray = ref([]);

import statics from "../configView/statics.json";
// const frequencies = computed(() => seatStore.frequencies);
const frequencies = computed(() => statics.frequencies);

const drag = ref(false);

const isStoped = computed(() => !seatStore.isServiceAvailable);

const showConfigPlanning = ref(false);
const open = () => {
  showConfigPlanning.value = true;
  initialize();
};
const close = () => {
  showConfigPlanning.value = false;
};

const cover = () => {
  ElMessageBox.confirm(
    "此操作会覆盖当前实际的席位状态并清空席位人员、清空扇区预设（如果有），可在“数据更新”被禁用时使用。",
    "确认要覆盖席位状态吗？",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning",
    }
  )
    .then(() => {
      // ElMessage({
      //   type: "success",
      //   message: "Delete completed",
      // });
      let changes = new Array();
      for (let i = 0; i < planningArray.value.length; i++) {
        let p = planningArray.value[i];
        if (p.frequency != p.planningFrequency) {
          // changes.push({
          //   seat: p.seatName,
          //   item: "planningFrequency",
          //   value: p.planningFrequency,
          // });
          changes.push({
            seat: p.seatName,
            item: "frequency",
            value: p.planningFrequency,
          });
        }
        if (
          p.sectorCodes.sort().toString() !=
          p.planningSectorCodes.sort().toString()
        ) {
          if (p.planningFrequency == null) {
            ElMessage({
              message: "请选择" + p.seatName + "席位的频率",
              type: "warning",
            });
            return null;
          } else {
            changes.push({
              seat: p.seatName,
              item: "sectorCodes",
              value: p.planningSectorCodes.sort(),
            });
          }
        }
      }
      if (changes.length == 0) {
        ElMessage({
          message: "请先修改扇区布局或频率",
          type: "warning",
        });
      } else {
        axios
          .post("api/seat_status_tma_set_planning.php?cover=yes", changes)
          .then((response) => {
            // console.log(response.data);
            ElMessage({
              message: "已覆盖当前扇区布局",
              type: "success",
            });
            seatStore.requestData();
            close();
          })
          .catch((error) => {
            console.warn(error);
          });
      }
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled",
      // });
    });
};

const save = () => {
  let changes = new Array();
  for (let i = 0; i < planningArray.value.length; i++) {
    let p = planningArray.value[i];
    if (p.frequency != p.planningFrequency) {
      // changes.push({
      //   seat: p.seatName,
      //   item: "planningFrequency",
      //   value: p.planningFrequency,
      // });
      changes.push({
        seat: p.seatName,
        item: "frequency",
        value: p.planningFrequency,
      });
    }
    if (
      p.sectorCodes.sort().toString() != p.planningSectorCodes.sort().toString()
    ) {
      if (p.planningFrequency == null) {
        ElMessage({
          message: "请选择" + p.seatName + "席位的频率",
          type: "warning",
        });
        return null;
      } else {
        changes.push({
          seat: p.seatName,
          item: "planningSectorCodes",
          value: p.planningSectorCodes.sort(),
        });
      }
    }
  }
  if (changes.length == 0) {
    ElMessage({
      message: "请先修改扇区布局或频率",
      type: "warning",
    });
  } else {
    axios
      .post("api/seat_status_tma_set_planning.php", changes)
      .then((response) => {
        // console.log(response.data);
        ElMessage({
          message: "已保存预设扇区布局",
          type: "success",
        });
        seatStore.requestData();
        close();
      })
      .catch((error) => {
        console.warn(error);
      });
  }
};

const clear = () => {
  axios
    .get("api/seat_status_tma_set_planning.php?clear=yes")
    .then((response) => {
      // console.log(response.data);
      ElMessage({
        message: "已清除预设扇区布局",
        type: "success",
      });
      seatStore.requestData();
      close();
    })
    .catch((error) => {
      console.warn(error);
    });
};

const initialize = () => {
  let status = seatStore.seatStatusFull.filter(
    (state) => state.orgGroup == "TMA" && state.sectorYes == 1
  );
  planningArray.value = [];
  for (let i = 0; i < status.length; i++) {
    if (status[i].seatType == "普通管制") {
      planningArray.value.push({
        seatName: status[i].seatName,
        logicSectorCode: status[i].logicSectorCode,
        sectorCodes: JSON.parse(JSON.stringify(status[i].sectorCodes)),
        planningSectorCodes:
          status[i].planningSectorCodes == null
            ? JSON.parse(JSON.stringify(status[i].sectorCodes))
            : JSON.parse(JSON.stringify(status[i].planningSectorCodes)),
        frequency: status[i].frequency,
        // planningFrequency:
        //   status[i].planningFrequency == null
        //     ? status[i].frequency
        //     : status[i].planningFrequency,
        planningFrequency: status[i].frequency,
      });
    }
  }
};

defineExpose({ open });
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.planner-wrapper-inner {
  column-count: 3;
  column-gap: 16px;
}

.planner-wrapper-seat {
  height: 100%;
  overflow: auto;
  margin-bottom: 16px;
  background-color: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(128, 128, 128, 0.2);
  border-radius: 4px;
  transition: all 0.5s ease-in-out;
}

.planner-wrapper-seat:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.planner-wrapper-seat-title {
  width: 100%;
  padding: 0 4px 0 12px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  /* font-weight: bold; */
  /* background-color: rgba(128, 128, 128, 0.3); */
  background-color: rgba(255, 255, 255, 0.03);
  border-bottom: 1px solid rgba(128, 128, 128, 0.2);
}

.planner-wrapper-seat-content {
  width: 100%;
  min-height: 36px;
  padding: 4px;
  text-align: justify;
  /* border: 1px solid #f66; */
}

.planner-sector-code {
  margin: 2px;
  padding: 0px 8px;
  font-size: 14px;
  user-select: none;
  cursor: pointer;
  font-family: "Consolas", "Courier New", monospace;
}

.planner-wrapper-command {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.planner-wrapper-command > * {
  margin: 0 8px;
}
</style>
